<!--
 * @Author: your name
 * @Date: 2020-05-29 16:46:57
 * @LastEditTime: 2020-06-04 16:48:59
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \mobile_project_200106\mobile_project\src\pages\logins\login.vue
--> 
<template>
  <div>
    <van-nav-bar title="登录" left-text="返回" left-arrow @click-left="back" />

     <van-form validate-first @submit="onSubmit">
      <!-- 通过 pattern 进行正则校验 -->

      <van-field
        v-model="loginFrom.username"
        name="username"
        label="用户名"
        placeholder="用户名"
        required
        :rules="[{ required: true, message: '请填写用户名' }]"
      />

      <van-field
        v-model="loginFrom.password"
        name="password"
        type="password"
        label="密码"
        placeholder="密码"
        required
        :rules="[{ required: true, message: '请填写密码' }]"
      />

      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { createNamespacedHelpers } from 'vuex'
const { mapMutations } = createNamespacedHelpers('userModule')
import * as api from "@/request/api/login.js"
export default {
  
  data(){
    return{
    loginFrom:{}
    }
  },
  methods: {
    ...mapMutations(["GET_TOKEN"]),
    back() {
      this.$router.go(-1);
    },
    async API_login(name,pwd){
      let result={
        name,
        pwd
      }
      return await api.login(result)
    },
    
   async onSubmit(){//登录按钮
   let {username,password}=this.loginFrom//结构赋值
      let res= await this.API_login(username,password)
      
      localStorage.setItem("shopToken",res.data.token)//存储token
      if(res.data.code===1000){
        this.GET_TOKEN(res.data.token)//vuex获取token
        // localStorage.setItem("token",res.data.token)//eventBus存储token
        // this.$eventBus.$emit("getToken",res.data.token)//eventBus获取token
        this.$toast.success("登录成功")
        this.$router.push("/user")
      }else{
        this.$toast.fail("账号或密码错误")
      }
      this.loginFrom={}
    }
  }
};
</script>

<style>
</style>